package de.grosjohann.android.feuerwehr.c2dm;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import de.grosjohann.android.feuerwehr.util.FileUtil;

public class C2DMRegistration {

  private static final String NAME = "C2DMRegistration";

  private static final String C2DM_REGISTRATION_DATA = "feuerwehr.C2DMRegistrationData";

  private static final String C2DM_REGISTRATION_ID = "registrationID";
  private static final String THIRD_PARTY_REGISTRATION = "thirdPartyRegistration";

  private static C2DMRegistration registration;
  private final Context context;

  private String registrationID = "";
  private boolean thirdPartyRegistration = false;

  private C2DMRegistration(Context ctx) {
    context = ctx;

    String registraionData = FileUtil.readFile(context, C2DM_REGISTRATION_DATA);
    try {
      JSONObject jsonObj = new JSONObject(registraionData);
      registrationID = jsonObj.getString(C2DM_REGISTRATION_ID);
      thirdPartyRegistration = jsonObj.getBoolean(THIRD_PARTY_REGISTRATION);
    } catch (JSONException ex) {
      Log.e(NAME, ex.getMessage());
    }

  }

  public static C2DMRegistration getInstance(Context ctx) {
    if (registration == null) {
      registration = new C2DMRegistration(ctx);
    }

    return registration;
  }

  public void setRegistrationID(String newRegistrationID) {
    registrationID = newRegistrationID;
    save();
  }

  public String getRegistrationID() {
    return registrationID;
  }

  public void deleteRegistrationID() {
    registrationID = "";
    save();
  }

  public void setThirdPartyRegistration(boolean registered) {
    thirdPartyRegistration = registered;
    save();
  }

  public void deleteThirdPartyRegistration() {
    thirdPartyRegistration = false;
    save();
  }

  public boolean isRegistrationUncomplete() {
    return !registrationID.isEmpty() && !thirdPartyRegistration;
  }

  public boolean isUnregistrationUncomplete() {
    return registrationID.isEmpty() && thirdPartyRegistration;
  }

  private void save() {
    synchronized (this) {
      try {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(C2DM_REGISTRATION_ID, registrationID);
        jsonObj.put(THIRD_PARTY_REGISTRATION, thirdPartyRegistration);

        FileUtil.writeFile(context, C2DM_REGISTRATION_DATA, jsonObj.toString());
      } catch (Exception ex) {
        Log.e(NAME, ex.getMessage());
      }
    }
  }
}
